<template>
  <el-dialog
    :title="`表数据 - ${currentTableName}`"
    v-model="dialogVisible"
    width="90%"
    :before-close="handleClose"
  >
    <!-- 表格 -->
    <div class="table-container">
      <el-table
        :data="tableData"
        style="width: 100%; height: 400px; overflow-y: auto;"
        stripe
        border
        highlight-current-row
      >
        <!-- 动态列 -->
        <el-table-column
          v-for="column in columns"
          :key="column"
          :prop="column"
          :label="column"
        />
        <!-- 操作列 -->
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="scope">
            <el-button type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        background
        layout="prev, pager, next, jumper, total"
        :total="total"
        :page-size="queryParams.pageSize"
        :current-page="queryParams.pageNum"
        @current-change="handlePageChange"
      />
    </div>
  </el-dialog>

  <!-- 编辑对话框 -->
  <el-dialog
    title="编辑数据"
    v-model="editDialogVisible"
    width="50%"
    @close="handleEditDialogClose"
  >
     
      <el-form :model="editFormData">
        <el-form-item v-for="column in columns" :key="column" :label="column">
          <el-input v-model="editFormData[column]" />
        </el-form-item>
      </el-form>
    
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSaveEdit">保存</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref } from 'vue';
import axios from 'axios';
import request from '../utils/request';
import { ElMessage, ElMessageBox } from 'element-plus';

const props = defineProps({
  tableName: String, // 表名
});

const dialogVisible = ref(false); // 弹窗显示状态
const tableData = ref([]); // 表格数据
const columns = ref([]); // 动态列名
const total = ref(0); // 总条数
const currentTableName = ref(''); // 当前表名
const tableKey = ref(''); // 当前表名

const queryParams = ref({
  pageNum: 1,
  pageSize: 15,
  tableName: '',
});

const editDialogVisible = ref(false); // 编辑对话框显示状态
const editFormData = ref({}); // 编辑表单数据

// 打开弹窗
const openDialog = async (tableName,primaryKey) => {
  currentTableName.value = tableName;
  tableKey.value = primaryKey;
  queryParams.value.tableName = tableName;
  dialogVisible.value = true;
  await fetchTableData();
};

// 关闭弹窗
const handleClose = () => {
  dialogVisible.value = false;
  tableData.value = [];
};

// 获取表数据
const fetchTableData = async () => {
  try {
    const response = await request.post("/table/getTableData", queryParams.value);
    tableData.value = response.data.records;
    total.value = response.data.total;
debugger;
    // 动态获取列名
    if (tableData.value.length > 0) {
      columns.value = Object.keys(tableData.value[0]);
    }
  } catch (error) {
    console.error('获取表数据失败:', error);
  }
};

// 分页
const handlePageChange = (pageNum) => {
  queryParams.value.pageNum = pageNum;
  fetchTableData();
};

// 编辑操作
const handleEdit = (row) => {
  editFormData.value = { ...row };
  editDialogVisible.value = true;
};

// 关闭编辑对话框
const handleEditDialogClose = () => {
  editDialogVisible.value = false;
};

// 保存编辑数据
const handleSaveEdit = async () => {
  try {
    debugger;
    const response = await request.post("/table/updateData", {
      tableName: currentTableName.value,
      data: editFormData.value,
      tablekey: tableKey.value
    });

    if (response.data.success) {
      ElMessage.success(response.data.message);
    }else{
      ElMessage.error(response.data.message);
    }
    
    if (response.data.success) {
      // 刷新表格数据
      await fetchTableData();
      editDialogVisible.value = false;
    } else {
      console.error('更新数据失败:', response.data.message);
    }
  } catch (error) {
    console.error('更新数据请求出错:', error);
  }
};

// 删除操作
const handleDelete = async (row) => {
  try {
    debugger;
      editFormData.value = { ...row };
        const response = await request.post("/table/deleteId", {
          tableName: currentTableName.value,
          data: editFormData.value,
          tablekey: tableKey.value
        });

        if (response.data.success) {
          ElMessage.success(response.data.message);
        }else{
          ElMessage.error(response.data.message);
        }

        if (response.data.success) {
          // 刷新表格数据
          await fetchTableData();
          editDialogVisible.value = false;
        } else {
          console.error('更新数据失败:', response.data.message);
        }
  } catch (error) {
      console.error('更新数据请求出错:', error);
  }
  
  // 调用删除接口
};

defineExpose({
  openDialog,
});
</script>

<style scoped>
.table-container {
  margin-bottom: 20px; /* 为分页模块留出空间 */
}

.pagination-container {
  display: flex;
  justify-content: center; /* 水平居中 */
  background: white;
  padding: 10px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}
</style>



<style scoped>
.table-container {
  margin-bottom: 20px; /* 为分页模块留出空间 */
}

.pagination-container {
  display: flex;
  justify-content: center; /* 水平居中 */
  background: white;
  padding: 10px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}
</style>